package com.czkevin.cif.crafting.gui;

import com.czkevin.cif.CustomItemFramework;
import com.czkevin.cif.crafting.RecipeMatch;
import com.czkevin.cif.crafting.RecipeRegister;
import org.bukkit.Bukkit;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack;
import com.czkevin.guicontrolsapi.Window;

public class AdvancedCraftingGUI extends Window {

    private final CraftingMatrixControl crafting = new CraftingMatrixControl(5, 5);
    private final CraftingOutputControl output = new CraftingOutputControl();

    private RecipeMatch currentMatched = null;

    public AdvancedCraftingGUI() {
        super("\u00a7f\uf808\uef01", 8, 5);
        output.setCallback(() -> {
            if(currentMatched == null) return false;
            currentMatched.recipe.removeLayer(crafting.getMatrix(), currentMatched);
            crafting.applyMatrixToDisplay();
            Bukkit.getScheduler().runTaskLater(CustomItemFramework.getInstance(), () -> refreshMatch(crafting.getMatrix()), 1L);
            return true;
        });
        crafting.setCallback(this::refreshMatch);
        setControl(0, 0, crafting);
        setControl(6, 2, output);
    }

    public void refreshMatch(ItemStack[][] matrix) {
        currentMatched = RecipeRegister.match(matrix);
        if(currentMatched == null) {
            output.setOutput(null);
            return;
        }
        CustomItemFramework.debug(String.format("Matched <%s> at (%d, %d)", currentMatched.recipe.getName(), currentMatched.x, currentMatched.y));
        output.setOutput(currentMatched.recipe.getClonedOutput());
    }

    @Override
    public void onOpenInternal(HumanEntity humanEntity) { }

    @Override
    protected boolean onCloseInternal(HumanEntity humanEntity) {
        crafting.dropAll(humanEntity.getLocation());
        return true;
    }
}
